//
//  NSObject+HDCommunityManager.m
//  app
//
//  Created by D on 15/8/20.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDCommunityManager.h"
#import "SNFmdbManager.h"
#import "HDMyCommunityModel.h"

@interface HDCommunityManager ()

@property (nonatomic,strong) JKHttpClient * jkHttp;
@property (nonatomic,strong) SNUniteUrl * uniteUrl;
@property (nonatomic,strong) NSMutableArray * mutableArray;
@property (nonatomic,strong) SNFmdbManager * snFmdbManager;
@property (nonatomic,strong) NSArray * dataArray;
@property (nonatomic,strong) NSString * isRefresh;
@property (nonatomic,strong) NSData * myData;
@property (nonatomic,assign) BOOL includeCommunity;
@property (nonatomic,assign) BOOL includeCommunityData;

@end


@implementation HDCommunityManager

+(HDCommunityManager *)shareManager
{
    AS_SINGLETON(HDCommunityManager, manager, {
        
        manager = [[HDCommunityManager alloc]init];
        manager.jkHttp = [[JKHttpClient alloc]init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
        manager.mutableArray = [NSMutableArray array];
        manager.dataArray = [NSArray array];
        manager.snFmdbManager = [SNFmdbManager shareManager];
    
    })
    
    return manager;
}

-(void)loadCommunityData:(HDCommunityResult *)result Refresh:(NSString *)refresh
{
    self.isRefresh = refresh;
    
    if ([self.jkHttp isRunning]) {
        return;
    }
    
    [self.jkHttp get:self.uniteUrl.my_community params:nil result:^(JKResponse *resp) {
       
        if (resp.OK) {
            result.success = YES;
            result.isFresh = refresh;
            DLog(@"content = %@",resp.content);
            if ([resp.content[@"list"]count] > 0) {
                [self communityDataSourceWithArray:resp.content[@"list"]];
                result.haveData = YES;
            }else
            {
                result.haveData = NO;
            }
            
            
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
        
    }];
    
    
    
}

-(void)chooseCommunity:(HDCommunityResult*)result Params:(NSDictionary*)params Com:(NSString*)community
{
    if ([self.jkHttp isRunning]) {
        return;
    }
    
    [self.jkHttp get:self.uniteUrl.my_community_houselist params:params result:^(JKResponse *resp) {
        
        if (resp.OK) {
            result.success = YES;
            [self updataCurrentCommunityDB:[params objectForKey:@"id"]];
            result.house_id = [params objectForKey:@"id"];
            result.cmid = [params objectForKey:@"cmid"];
            result.community_name = community;
           
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
        
    }];

}



-(NSMutableArray*)communityDataSourceWithArray:(NSArray*)array
{
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"communityLastRefreshTime"];
    [self.mutableArray removeAllObjects];
    
    [self createFmdb];
    
    for (int i = 0 ; i < array.count; i++) {
        NSDictionary * dict = [array objectAtIndex:i];
        HDMyCommunityModel * model = [HDMyCommunityModel modelWithDict:dict];
        [self.mutableArray addObject:model];
        
        [self saveDataToDB: model ];
    }
    
    
    return self.mutableArray;
}


#pragma mark - 创建表
- (void)createFmdb
{
    NSString * sql_cList = [NSString stringWithFormat:@"create table if not exists Community_%@(id TEXT PRIMARY KEY ,cmid TEXT,community_name TEXT ,house_name TEXT, selected TEXT,delSign TEXT);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    [self.snFmdbManager createTableWithSql:sql_cList];
    sql_cList = [NSString stringWithFormat:@"delete from Community_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    [self.snFmdbManager createTableWithSql:sql_cList];
}


#pragma mark - 保存到数据库
-(void)saveDataToDB:(HDMyCommunityModel*)model
{
    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString * sql = [NSString stringWithFormat:@"insert into Community_%@(id  ,cmid ,community_name  ,house_name , selected , delSign )values (?, ?, ?, ?, ?, ?);",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
        
            self.dataArray = @[model.house_id,model.cmid,model.community_name,model.house_name,model.selected,@"000"];
     
        if ([db executeUpdate:sql withArgumentsInArray:self.dataArray]) {
            DLog(@"保存到了 mycommunity表");
        }
    }];

    
}

//#pragma mark - 更新数据库
//-(void)updataToDB:(HDMyCommunityModel*)model
//{
//    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        NSString * sql = [NSString string];
//        
//        sql = [NSString stringWithFormat:@"UPDATE Community_%@ SET id = '%@', cmid = '%@',community_name = '%@',house_name = '%@',selected = '%@',delSign = '%@' WHERE id = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],model.house_id,model.cmid,model.community_name,model.house_name,model.selected,@"000",model.house_id];
//
//        if ([db executeUpdate:sql]) {
//            DLog(@"更新ChatList表成功");
//        }
//        
//    }];
//
//}

#pragma mark - 删除更新
-(void)updataAndDeleteToCommunityDB:(NSString*)houseId
{
    NSString * sql = [NSString stringWithFormat:@"UPDATE Community_%@ SET delSign = '%@' WHERE id = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],@"111",houseId];
    [self.snFmdbManager performExecuteUpdateWithSql:sql];
}

#pragma mark - 更新当前小区
-(void)updataCurrentCommunityDB:(NSString*)houseId
{
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString * sql = [NSString stringWithFormat:@"UPDATE Community_%@ SET selected = '%@' WHERE id = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],@"0",[[NSUserDefaults standardUserDefaults]objectForKey:@"currentCom"]];
        if ([db executeUpdate:sql]) {
            
            NSString * sql2 = [NSString stringWithFormat:@"UPDATE Community_%@ SET selected = '%@' WHERE id = '%@' ",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],@"1",houseId];
            if ([db executeUpdate:sql2]) {
                DLog(@"更新当前小区成功");
                
                
                
            }
            
            
            
        }
        
    }];
    
}


#pragma mark - 从数据库中读取数据
- (NSMutableArray *)arrayFromFmdb
{
    NSMutableArray * arr1 = [NSMutableArray array];
    NSMutableArray * arr2 = [NSMutableArray array];
    [self.snFmdbManager.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString* sql_one = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'Community_%@';",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        FMResultSet * set_one = [db executeQuery:sql_one];
        if ([set_one next]){
            NSString * sql = [NSString stringWithFormat: @"select * from Community_%@;",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
            FMResultSet * set = [db executeQuery:sql];
           [self.mutableArray removeAllObjects];
            while ([set next]) {
                
                NSString * house_id = [set stringForColumn:@"id"];
                NSString * cmid = [set stringForColumn:@"cmid"];
                NSString * community_name = [set stringForColumn:@"community_name"];
                NSString * house_name = [set stringForColumn:@"house_name"];
                NSString * selected = [set stringForColumn:@"selected"];
                NSString * delSign = [set stringForColumn:@"delSign"];
                
                NSDictionary * dict = @{@"id":house_id,
                                        @"cmid":cmid,
                                        @"community_name":community_name,
                                        @"house_name":house_name,
                                        @"selected":selected,
                                        @"delSign":delSign};
                
                
                [arr1 addObject:dict];
                
            }
            [set close];
        }
        [set_one close];
        //        [db close];
    }];

    


    
    [arr2 addObjectsFromArray:arr1];
    for (int i = 0 ; i < arr2.count; i ++) {
        DLog(@"排序前--> %@",[[arr2 objectAtIndex:i]objectForKey:@"dateline" ] );
        
    }
    
    NSSortDescriptor*sorter=[[NSSortDescriptor alloc]initWithKey:@"dateline" ascending:NO];
    NSMutableArray *sortDescriptors=[[NSMutableArray alloc]initWithObjects:&sorter count:1];
    NSArray *sortArray=[arr2 sortedArrayUsingDescriptors:sortDescriptors];
    
    for (int i=0; i<[sortArray count]; i++) {
        NSLog(@"排序后----->>%@",[[sortArray objectAtIndex:i] objectForKey:@"dateline"]);
        if ([[[sortArray objectAtIndex:i] objectForKey:@"delSign"]integerValue] == 000) {
            [self.mutableArray addObject:[HDMyCommunityModel modelWithDict:[sortArray objectAtIndex:i]]];
        }
        
    }
    
    return self.mutableArray;
}
#pragma mark - 表是否存在
- (BOOL)fmdbIncludeCommunity
{
    NSString * tablename = [NSString stringWithFormat:@"Community_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager fmdbIncludetableWithTableName:tablename];
}

#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeCommunityData
{
    NSString * tablename = [NSString stringWithFormat:@"Community_%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager tabelIncludeDataWithTableName:tablename];
}


#pragma mark - 是否自动刷新数据
- (BOOL)shouldRefreshCommunityData
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        if ([self fmdbIncludeCommunity]) {//表是存在的
            //通过时间判断是否需要自动刷新
            NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
            NSDate * participationLastRefreshTime = [ud objectForKey:@"communityLastRefreshTime"];
            NSDate * nowDate = [NSDate date];
            NSTimeInterval aTimer = [nowDate timeIntervalSinceDate:participationLastRefreshTime];
            if (aTimer > 86400) {//已经有一段时间没有刷新了,需要自动刷新
                DLog(@"Community需要自动刷新");
                return YES;
            } else {//不需要自动刷新
                DLog(@"Community不需要自动刷新");
                return NO;
            }
        } else {//表不存在,第一次进入此页面
            return YES;
        }
    } else {//数据库文件都不存在,第一次进入这个页面
        return YES;
    }
}


@end














